<?php
class User extends CActiveRecord
{
	const STATUS_NOACTIVE=0;
	const STATUS_ACTIVE=1;
	const STATUS_BANED=-1;
	
	/**
	 * The followings are the available columns in table 'users':
	 * @var integer $id
	 * @var string $username
	 * @var string $password
	 * @var string $firstname
	 * @var string $lastname
	 * @var string $sex
	 * @var string $phone
	 * @var string $birthday
	 * @var string $avata
	 * @var string $adrress
	 * @var string $city
	 * @var string $country_id
	 * @var string $company
	 * @var string $email
	 * @var string $activkey
	 * @var integer $createtime
	 * @var integer $lastvisit
	 * @var integer $superuser
	 * @var integer $status
	 */

	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return Yii::app()->getModule('user')->tableUsers;
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		
		return ((Yii::app()->getModule('user')->isAdmin())?array(
			#array('username, password, email', 'required'),
			array('username', 'length', 'max'=>20, 'min' => 3,'message' => UserModule::t("Incorrect username (length between 3 and 20 characters).")),
			array('password', 'length', 'max'=>128, 'min' => 4,'message' => UserModule::t("Incorrect password (minimal length 4 symbols).")),
			array('email', 'email'),
			array('username', 'unique', 'message' => UserModule::t("This user's name already exists.")),
			array('email', 'unique', 'message' => UserModule::t("This user's email address already exists.")),
			array('username', 'match', 'pattern' => '/^[A-Za-z0-9_]+$/u','message' => UserModule::t("Incorrect symbols (A-z0-9).")),
			array('status', 'in', 'range'=>array(self::STATUS_NOACTIVE,self::STATUS_ACTIVE,self::STATUS_BANED)),
			array('superuser', 'in', 'range'=>array(0,1)),
			array('username, email, createtime, lastvisit, superuser, status', 'required'),
			array('createtime, lastvisit, superuser, status', 'numerical', 'integerOnly'=>true),
		):((Yii::app()->user->id==$this->id)?array(
			array('roles, country_id', 'safe'),
			array('username, email, firstname, lastname,country_id', 'required'),
			array('username', 'length', 'max'=>20, 'min' => 3,'message' => UserModule::t("Incorrect username (length between 3 and 20 characters).")),
			array('email', 'email'),
			array('email', 'unique', 'message' => UserModule::t("This user's email already exists.")),
			array('username', 'match', 'pattern' => '/^[A-Za-z0-9_]+$/u','message' => UserModule::t("Incorrect symbols (A-z0-9).")),
			array('email', 'unique', 'message' => UserModule::t("This user's email address already exists.")),
			array('sex', 'in', 'range'=>array(0,1,2,3,4)),
			array('firstname', 'length', 'max'=>128, 'min' => 2,'message' => UserModule::t("Incorrect firstname (minimal length 2 symbols).")),
			array('lastname', 'length', 'max'=>128, 'min' => 2,'message' => UserModule::t("Incorrect lastname (minimal length 2 symbols).")),
			array('adrress', 'length', 'max'=>255,'message' => UserModule::t("Incorrect adrress (max length 255 symbols).")),
			array('avata', 'length', 'max'=>255,'message' => UserModule::t("Incorrect avata (max length 255 symbols).")),
			array('company', 'length', 'max'=>255,'message' => UserModule::t("Incorrect company (max length 255 symbols).")),
			array('city', 'length', 'max'=>255,'message' => UserModule::t("Incorrect city (max length 255 symbols).")),
			array('company', 'length', 'max'=>255,'message' => UserModule::t("Incorrect company (max length 255 symbols).")),
		):array()));
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
    	Yii::import('application.modules.user.models.AuthAssignment');
		$relations = array(
			'profile'=>array(self::HAS_ONE, 'Profile', 'user_id'),
			'country'=>array(self::BELONGS_TO, 'Country', 'country_id'),
			'roles' => array(self::HAS_MANY, 'AuthAssignment', 'userid')//create new property roles
		);
		if (isset(Yii::app()->getModule('user')->relations)) $relations = array_merge($relations,Yii::app()->getModule('user')->relations);
		return $relations;
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'username'=>UserModule::t("User name"),
			'password'=>UserModule::t("Password"),
			'verifyPassword'=>UserModule::t("Retype Password"),
			'email'=>UserModule::t("E-mail"),
			'verifyCode'=>UserModule::t("Verification Code"),
			'id' => UserModule::t("Id"),
			'activkey' => UserModule::t("activation key"),
			'createtime' => UserModule::t("Registration date"),
			'lastvisit' => UserModule::t("Last visit"),
			'country_id' => UserModule::t("Country"),
			'superuser' => UserModule::t("Superuser"),
			'status' => UserModule::t("Status"),
			'roles' => UserModule::t("Roles"),
		);
	}
	
	public function scopes()
	{
			return array(
					'active'=>array(
							'condition'=>'status='.self::STATUS_ACTIVE,
					),
					'notactvie'=>array(
							'condition'=>'status='.self::STATUS_NOACTIVE,
					),
					'banned'=>array(
							'condition'=>'status='.self::STATUS_BANED,
					),
					'superuser'=>array(
							'condition'=>'superuser=1',
					),
					'notsafe'=>array(
						'select' => 'id, username, password, email, activkey, createtime, lastvisit, superuser, status, country_id',
					),
			);
	}
	
	public function defaultScope()
    {
        return array(
            'select' => 'id, username, email, createtime, lastvisit, superuser, status, country_id',
        );
    }
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria = new CDbCriteria;

		$criteria->compare('t.id', $this->id);
		$criteria->compare('t.username', $this->username, true);
		$criteria->compare('t.password', $this->password, true);
		$criteria->compare('t.country_id', $this->country_id, true);
		//$criteria->compare('t.tel', $this->tel, true);
		//use roles property
		$criteria->compare('roles.itemname', $this->roles, true, 'OR');
		$criteria->compare('country.name', $this->country, true, 'OR');
		$criteria->with = array('roles', 'country');

		return new CActiveDataProvider($this, array(
			'criteria' => $criteria,
		));
	}
	
	public function getUserRoleName($id=Null) {
		if(is_null($id))	$id=$this->id;
		if ($AuthassignmentModel=AuthAssignment::Model()->findByAttributes(array('userid'=>$id))) {
			$roleName = $AuthassignmentModel->itemname;
		}
		return(isset($roleName)) ? ($roleName) : "-----";
	}
	public function getRolesAsListData()
	{
		$roles = Yii::app()->authManager->getRoles();
		return CHtml::listData($roles,'name','name');    
	}
	
	public function getCountryName($country_id=null) {
		$countryName = Country::model()->findbyPk($country_id);
		return $countryName->name;
	}
	public function getCountryNameAsListData()
	{
		$countryName = Country::model()->findAll();
		return CHtml::listData($countryName,'id','name');    
	}
	public static function itemAlias($type,$code=NULL) {
		$_items = array(
			'UserStatus' => array(
				self::STATUS_NOACTIVE => UserModule::t('Not active'),
				self::STATUS_ACTIVE => UserModule::t('Active'),
				self::STATUS_BANED => UserModule::t('Banned'),
			),
			'AdminStatus' => array(
				'0' => UserModule::t('No'),
				'1' => UserModule::t('Yes'),
			),
			'UserSexs' => array(
				'0' => UserModule::t('Male'),
				'1' => UserModule::t('Female'),
			),
		);
		if (isset($code))
			return isset($_items[$type][$code]) ? $_items[$type][$code] : false;
		else
			return isset($_items[$type]) ? $_items[$type] : false;
	}
}